package com.cap.dreamcircle.View;

import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.baoyz.actionsheet.ActionSheet;
import com.cap.dreamcircle.Base.BaseFragment;
import com.cap.dreamcircle.Model.Action.ActionSheetAction;
import com.cap.dreamcircle.Model.Action.DeleteFriendCircleAction;
import com.cap.dreamcircle.Model.Action.LikeDreamCircleAction;
import com.cap.dreamcircle.Model.Bean.BaseBean;
import com.cap.dreamcircle.Model.Bean.DreamCircleFriendsBean;
import com.cap.dreamcircle.Model.Bean.FriendsDreamEntity;
import com.cap.dreamcircle.Model.IDreamModel;
import com.cap.dreamcircle.Model.Impl.DreamModelImpl;
import com.cap.dreamcircle.R;
import com.cap.dreamcircle.Utils.CommonSubscriber;
import com.cap.dreamcircle.Utils.PreferenceUtils;
import com.cap.dreamcircle.Utils.SimpleMediaPlayerUtils;
import com.cap.dreamcircle.Utils.ToastUtils;
import com.cap.dreamcircle.Utils.TransformUtils;
import com.cap.dreamcircle.View.Adapter.SimpleFirendsDreamAdapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import de.greenrobot.event.EventBus;
import rx.Subscriber;
import rx.functions.Action0;

/**
 * Created by liucxu on 2017/6/22.
 */

public class FragmentDreamCircle extends BaseFragment {

    @BindView(R.id.recyclerview_dream_circle)
    RecyclerView recyclerview_dream_circle;
    @BindView(R.id.swipe_refrsh_dream_circle)
    SmartRefreshLayout swipe_refrsh_dream_circle;

    private List<FriendsDreamEntity> sources = new ArrayList<>();
    private SimpleFirendsDreamAdapter adapter;
    //    private LoadMoreUtil loadMoreUtil;
    private IDreamModel dreamModel;

    private int page_index = 1;
    private boolean is_refresh = true;

    @Override
    public int getLayoutId() {
        return R.layout.fragment_dream_circle;
    }

    @Override
    public void setupView() {
        ButterKnife.bind(this, mContextView);
        adapter = new SimpleFirendsDreamAdapter(getActivity(), sources);
        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        manager.setItemPrefetchEnabled(false);
        recyclerview_dream_circle.setLayoutManager(manager);
        recyclerview_dream_circle.setAdapter(adapter);
        dreamModel = new DreamModelImpl();
        swipe_refrsh_dream_circle.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                is_refresh = true;
                swipe_refrsh_dream_circle.setEnableLoadmore(true);
                requestDreamCircleRecords();
            }
        });
        swipe_refrsh_dream_circle.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                is_refresh = false;
                requestDreamCircleRecords();
            }
        });
        EventBus.getDefault().register(this);
    }

    @Override
    public void setupData() {

    }

    public void onEvent(final DeleteFriendCircleAction action) {
        MaterialDialog dialog = new MaterialDialog.Builder(getActivity()).title("提示").content("确定删除?").positiveText("确定").negativeText("取消").onPositive(new MaterialDialog.SingleButtonCallback() {
            @Override
            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                DeleteDreamCircleById(action.getDreamId(), action.getPosition());
            }
        }).build();
        dialog.show();
    }

    public void onEvent(LikeDreamCircleAction action) {
        likeDreamCircle(sources.get(action.getPosition()).getDreamId() + "", action.getPosition());
    }

    public void onEvent(final ActionSheetAction action) {
        if (PreferenceUtils.GetUserId().equals(action.getEntity().getDreamUserId())) {
            //自己的条目，actionsheet菜单中有删除、转发按钮
            ActionSheet.createBuilder(getActivity(), getActivity().getSupportFragmentManager())
                    .setCancelButtonTitle("取消")
                    .setOtherButtonTitles("删除")
                    .setCancelableOnTouchOutside(true)
                    .setListener(new ActionSheet.ActionSheetListener() {
                        @Override
                        public void onDismiss(ActionSheet actionSheet, boolean isCancel) {
                        }

                        @Override
                        public void onOtherButtonClick(ActionSheet actionSheet, int index) {
                            if (index == 0) {
                                MaterialDialog dialog = new MaterialDialog.Builder(getActivity()).title("提示").content("确定删除?").positiveText("确定").negativeText("取消").onPositive(new MaterialDialog.SingleButtonCallback() {
                                    @Override
                                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                        DeleteDreamCircleById(action.getEntity().getDreamId(), action.getPosition());
                                    }
                                }).build();
                                dialog.show();
                            }
                        }
                    }).show();
        } else {
            //别人的条目，actionsheet菜单中有举报按钮
            ActionSheet.createBuilder(getActivity(), getActivity().getSupportFragmentManager())
                    .setCancelButtonTitle("取消")
                    .setOtherButtonTitles("举报")
                    .setCancelableOnTouchOutside(true)
                    .setListener(new ActionSheet.ActionSheetListener() {
                        @Override
                        public void onDismiss(ActionSheet actionSheet, boolean isCancel) {
                        }

                        @Override
                        public void onOtherButtonClick(ActionSheet actionSheet, int index) {
                            if (index == 0) {
                                ReportDreamRecord(action.getEntity());
                            }
                        }
                    }).show();
        }
    }

    private void ReportDreamRecord(FriendsDreamEntity entity) {
        dreamModel.ReportDreamRecord(entity.getDreamId()).subscribe(new CommonSubscriber<BaseBean>() {
            @Override
            public void onSuccess(BaseBean response) {
                ToastUtils.showShortToast(getActivity(), "已经成功举报");
            }

            @Override
            public void onFailure(BaseBean response) {
                ToastUtils.showShortToast(getActivity(), response.getDesc());
            }
        });
    }

    private void likeDreamCircle(String dreamId, final int position) {
        dreamModel.LikeDreamCircleRecord(dreamId).compose(TransformUtils.<BaseBean>defaultSchedulers()).doOnSubscribe(new Action0() {
            @Override
            public void call() {
                showProgress();
            }
        }).subscribe(new Subscriber<BaseBean>() {
            @Override
            public void onCompleted() {
                hideProgress();
            }

            @Override
            public void onError(Throwable e) {
                hideProgress();
            }

            @Override
            public void onNext(BaseBean res) {
                hideProgress();
                if (res.getCode() == 0) {
                    adapter.resetItemLikedStatus(position);
                } else {
                    ToastUtils.showShortToast(getActivity(), res.getDesc());
                }
            }
        });
    }

    private void DeleteDreamCircleById(String id, final int position) {
        dreamModel.DeleteDreamCircleById(id).compose(TransformUtils.<BaseBean>defaultSchedulers()).doOnSubscribe(new Action0() {
            @Override
            public void call() {
                showProgress();
            }
        }).subscribe(new Subscriber<BaseBean>() {
            @Override
            public void onCompleted() {
                hideProgress();
            }

            @Override
            public void onError(Throwable e) {
                hideProgress();
            }

            @Override
            public void onNext(BaseBean response) {
                hideProgress();
                if (response.getCode() == 0) {
                    adapter.deleteItem(position);
                } else {
                    ToastUtils.showShortToast(getActivity(), response.getDesc());
                }
            }
        });
    }

    private void requestDreamCircleRecords() {
        int local_page = page_index;
        if (is_refresh) {
            local_page = 1;
        }
        dreamModel.RequestDreamCircleRecords(local_page).compose(TransformUtils.<DreamCircleFriendsBean>defaultSchedulers()).doOnSubscribe(new Action0() {
            @Override
            public void call() {
                showProgress();
            }
        }).subscribe(new Subscriber<DreamCircleFriendsBean>() {
            @Override
            public void onCompleted() {
                hideProgress();
                swipe_refrsh_dream_circle.finishRefresh();
            }

            @Override
            public void onError(Throwable e) {
                hideProgress();
                swipe_refrsh_dream_circle.finishRefresh();
            }

            @Override
            public void onNext(DreamCircleFriendsBean response) {
                hideProgress();
                swipe_refrsh_dream_circle.finishRefresh();
                swipe_refrsh_dream_circle.finishLoadmore();
                if ((response.getDreamRecord() != null) && (response.getDreamRecord().size() > 0)) {
                    if (is_refresh) {
                        sources.clear();
                        page_index = 1;
                    }
                    sources.addAll(response.getDreamRecord());
                    adapter.setDatas(sources);
                    adapter.notifyDataSetChanged();
                    page_index++;
                } else {
                    swipe_refrsh_dream_circle.finishLoadmore();
                    swipe_refrsh_dream_circle.setEnableLoadmore(false);
                }
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
//        showProgress();
        is_refresh = true;
        requestDreamCircleRecords();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        if (!hidden) {
            is_refresh = true;
            requestDreamCircleRecords();
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        SimpleMediaPlayerUtils.getInstance(getContext()).releaseMediaPlayer();
    }
}
